﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace D.Util.UtilExpression
{
    /// <summary>
    /// 正则表达式类
    /// </summary>
    public static class UtilExpression
    {
        /// <summary>
        /// 规则详情组装匹配的正则表达式
        /// </summary>
        /// <param name="ruleDetailDic"></param>
        /// <returns></returns>
        public static string ConvertRegularExpression(Dictionary<int, List<char>> ruleDetailDic)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("^");
            int lastIndex = 0;
            foreach (KeyValuePair<int, List<char>> item in ruleDetailDic)
            {
                int intervalPostion = item.Key - lastIndex-1;
                string itemValue = item.Value.Count > 1 ? $"[{string.Join(',', item.Value)}]" : item.Value[0].ToString();
                if (item.Key == 0|| intervalPostion==0)
                    sb.Append($"{itemValue}");
                else
                    sb.Append(".{" + intervalPostion + "}" + itemValue + "");

                lastIndex = item.Key;
            }
            sb.Append(".*$");
            return sb.ToString();
        }
    }
}
